package com.example.goodsserver.manager;

import com.example.goodsserver.vo.GoodsInfoVO;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 用户信息缓存
 *
 */
@Service
public class GoodsCacheManager {
    @Autowired
    private RedissonClient redissonClient;
    private static final String GOODS_INFO_CHACHE = "GOODS_INFO_CHACHE:%s";
    /**
     * 商品详情超时时间
     */
    @Value("${goodsInfoVO.cache.expire.minutes:1440}")
    private int expireMinutes;
    private static final Logger LOGGER = LoggerFactory.getLogger(GoodsCacheManager.class);
    /**
     * 获取缓存中的商品VO
     *
     * @param id
     * @return
     */
    public GoodsInfoVO getGoodsInfoCache(String id) {
        try {
            RBucket<GoodsInfoVO> keyObject =
                    redissonClient.getBucket(String.format(GOODS_INFO_CHACHE, id));
            return keyObject.get();
        } catch (Exception e) {
            LOGGER.error("GoodsCacheManager.getGoodsInfoCache 从缓存中获取数据异常，id:【{}】异常信息：", id, e);
            return null;
        }
    }

    public void saveGoodsInfoVOCache(String id, GoodsInfoVO goodsInfoVODB) {
        if (id == null || goodsInfoVODB == null) {
            return;
        }
        RBucket<GoodsInfoVO> keyObject =
                redissonClient.getBucket(String.format(GOODS_INFO_CHACHE, id));
        keyObject.set(goodsInfoVODB,
                expireMinutes,
                TimeUnit.MINUTES);
    }
}
